package com.jzo2o.foundations.service.impl;

import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.dto.response.ServeCategoryResDTO;
import com.jzo2o.foundations.model.dto.response.ServeSimpleResDTO;
import com.jzo2o.foundations.service.HomeService;
import com.jzo2o.foundations.service.IRegionService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

//门户查询接口
public class HomeServiceImpl implements HomeService {


    @Resource
    private ServeMapper serveMapper;

    @Resource
    private IRegionService regionService;

    /**
     * 根据区域id获取首页服务
     * @param regionId
     * @return
     */

    @Caching(
            cacheable = {
                    //result返回值为null的时候 属于缓存穿透的情况 缓存时间30分钟
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON,key = "#regionId",unless = "#result.size()!=0",
                    cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),//定义缓存数据为空 处理缓存穿透

                    //正常情况下 缓存永不过期

                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON,key = "#regionId",unless = "#result.size()==0",
                            cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
    @Override
    public List<ServeCategoryResDTO> queryServeIconCategoryByRegionIdCache(Long regionId) {

        //先确定是否启用该区域
        Region region = regionService.getById(regionId);
        if(ObjectUtils.isNull(region) || region.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()){
            return Collections.emptyList();
        }

        //检查首页服务列表
        List<ServeCategoryResDTO> list = serveMapper.findServeListByRegionId(regionId);
        if(CollUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        //对查询到的数据进行处理 最多包含两个服务类型
        int endIndex = list.size() >= 2?2:list.size();
        List<ServeCategoryResDTO> serveCategoryResDTOS = new ArrayList<>(list.subList(0, endIndex));

        serveCategoryResDTOS.forEach(item->{
            List<ServeSimpleResDTO> serveResDTOList = item.getServeResDTOList();//每种服务类型最多含有4个服务项
            int endIndex2 = serveResDTOList.size()>=4?4:serveResDTOList.size();
            List<ServeSimpleResDTO> serveSimpleResDTOS = new ArrayList<>(serveResDTOList.subList(0, endIndex2));
            item.setServeResDTOList(serveSimpleResDTOS);
        });
        return serveCategoryResDTOS;
    }
}
